package org.nowcoder.leetcode.bit;

/**
 * Title  : 67. Add Binary
 * Source : https://leetcode.cn/problems/add-binary/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-08-26
 */

public class LeetCode_67 {
    public String addBinary(String a, String b) {
        //模拟算术加法
        StringBuilder builder = new StringBuilder();
        int bit = 0; //进位
        int i = a.length() - 1, j = b.length() - 1;
        for (; i >= 0 && j >= 0; i--, j--) {
            int op1 = a.charAt(i) - '0';
            int op2 = b.charAt(j) - '0';
            int sum = op1 + op2 + bit;
            if (sum == 3) {
                builder.append('1');
                bit = 1;
            } else if (sum == 2) {
                builder.append('0');
                bit = 1;
            } else if (sum == 1) {
                builder.append('1');
                bit = 0;
            } else {
                builder.append('0');
                bit = 0;
            }
        }

        String temp = a;
        int k = i;
        if (j >= 0) {
            temp = b;
            k = j;
        }
        for (; k >= 0; k--) {
            int op1 = temp.charAt(k) - '0';
            int sum = op1 + bit;
            if (sum == 2) {
                builder.append('0');
                bit = 1;
            } else if (sum == 1) {
                builder.append('1');
                bit = 0;
            } else {
                builder.append('0');
                bit = 0;
            }
        }
        if (bit == 1) builder.append('1');
        return builder.reverse().toString();
    }
}
